package com.cosytek.farmmanager;

import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

import com.cosytek.farmmanager.autoupgrade.UpdateManager;
import com.cosytek.farmmanager.data.Main;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends ActionBarActivity implements OnFragmentInteractionListener, View.OnClickListener {

    public static final  String UPDATE_PATH = "/apk/latest";

    private View mTabBarView;
    private String mToken;
    private Button mBtnFarmView;
    private Button mBtnMessageView;
    private ArrayList<Button> mButtonList;
    private UpdateManager mUpdateManager;

    private MainFragment mFragmentMain;
    private Fragment mFragmentMsg;
    private FarmFragment fragmentFarm;
    private TaskFragment fragmentTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTabBarView = this.findViewById(R.id.tab_bar);
        mTabBarView.setVisibility(View.GONE);

        mBtnFarmView = (Button)this.findViewById(R.id.main_activity_btn_farm);
        mBtnMessageView = (Button)this.findViewById(R.id.main_activity_btn_msg);

        mButtonList = new ArrayList<Button>();
        mButtonList.add(mBtnFarmView);
        mButtonList.add(mBtnMessageView);

        mBtnFarmView.setOnClickListener(this);
        mBtnMessageView.setOnClickListener(this);

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, LoginFragment.newInstance(this))
                    .commit();
        }
        String serverAddress = FarmManagerApp.getAppContext().getString(R.string.server_address);
        mUpdateManager = new UpdateManager(this, serverAddress + UPDATE_PATH);
        mUpdateManager.startCheck();

        createCoreFragment();
    }

    private void createCoreFragment() {
        mFragmentMain = MainFragment.newInstance();
        mFragmentMsg = MsgFragment.newInstance();
    }

    private void selectButton(Button b) {
        for(Button btn: mButtonList) {
            if (b == btn) {
                btn.setSelected(true);
            } else {
                btn.setSelected(false);
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onFragmentInteraction(Fragment f, Uri uri) {
        String path = uri.getPath();
        switch (path) {
            case LoginFragment.PATH_LOGIN:
                String token = uri.getQueryParameter("token");
                mToken = token;

                onLoginOK();
                break;
        }
    }

    private void onLoginOK() {
        mTabBarView.setVisibility(View.VISIBLE);
        selectButton(mBtnFarmView);

        prevHideAllFragments();

        getSupportFragmentManager().beginTransaction()
                .replace(R.id.container, mFragmentMain).add(R.id.container, mFragmentMsg)
                .show(mFragmentMain).hide(mFragmentMsg)
                .commit();

        WebSocketService.stopWebSocketService(this);
        WebSocketService.startWebSocketService(this);

        // load new message
        MsgManager.instance().loadUnreadMsgFromServer(mToken);
    }

    public String getToken() {
        return mToken;
    }

    @Override
    public void onClick(View v) {
        selectButton((Button)v);

        prevHideAllFragments();
        switch (v.getId()) {
            case R.id.main_activity_btn_farm:
                getSupportFragmentManager().beginTransaction()
                        .show(mFragmentMain).hide(mFragmentMsg)
                        .commit();
                break;
            case R.id.main_activity_btn_msg:
                getSupportFragmentManager().beginTransaction()
                        .show(mFragmentMsg).hide(mFragmentMain)
                        .commit();
                break;
        }
    }

    private void prevHideAllFragments() {
        List<Fragment> fl = getSupportFragmentManager().getFragments();
        android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        for(Fragment f : fl) {
            ft.hide(f);
        }

        ft.commit();
    }

    public void showFarmFragment(String farmId) {
        prevHideAllFragments();

        if (fragmentFarm == null) {
            fragmentFarm = FarmFragment.newInstance(farmId);
            getSupportFragmentManager().beginTransaction().add(R.id.container, fragmentFarm)
                    .show(fragmentFarm).commit();
        } else {
            fragmentFarm.updateFarm(farmId);
            getSupportFragmentManager().beginTransaction().show(fragmentFarm).commit();
        }
    }

    public void showTaskFragment(String farmId, String taskId) {
        prevHideAllFragments();

        if (fragmentTask == null) {
            fragmentTask = TaskFragment.newInstance(farmId, taskId);
            getSupportFragmentManager().beginTransaction().add(R.id.container, fragmentTask)
                    .show(fragmentTask).commit();
        } else {
            fragmentTask.updateTask(farmId, taskId);
            getSupportFragmentManager().beginTransaction().show(fragmentTask).commit();
        }
    }

    public Main getMain() {
        if (mFragmentMain == null) {
            return null;
        }
        return mFragmentMain.getMain();
    }
}
